package com.hnjd.controller;

import com.hnjd.controller.utils.R;
import com.hnjd.service.IAdminService;
import com.hnjd.service.IStudentService;
import com.hnjd.service.ITeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class LoginController {

    private IAdminService adminService;
    private ITeacherService teacherService;
    private IStudentService studentService;

    @Autowired
    public void setAdminService(IAdminService adminService) {
        this.adminService = adminService;
    }

    @Autowired
    public void setTeacherService(ITeacherService teacherService) {
        this.teacherService = teacherService;
    }

    @Autowired
    public void setStudentService(IStudentService studentService) {
        this.studentService = studentService;
    }

    @PostMapping("/login")
    public R login(String username, String password, String role, HttpServletResponse response, HttpServletRequest request){
        int login=0;
        if (role.equals("admin")) {
            login = adminService.login(username, password);
        }else if(role.equals("teacher")){
            login = teacherService.login(username,password);
        }else {
            login =  studentService.login(username,password);
        }
        System.out.println(login);
        if(login!=0){
            System.out.println("存储cookie");
            Cookie username1 = new Cookie("username", username);
            Cookie password1 = new Cookie("password", password);
            Cookie role1 = new Cookie("role", role);
            //webapp文件下所有应用共享cookie
            username1.setPath("/");
            password1.setPath("/");
            role1.setPath("/");
            if(role.equals("admin")){
                username1.setMaxAge(-1);
                password1.setMaxAge(-1);
                role1.setMaxAge(-1);
            }else {
                username1.setMaxAge(60*60*24*7);
                password1.setMaxAge(60*60*24*7);
                role1.setMaxAge(60*60*24*7);
            }
            response.addCookie(username1);
            response.addCookie(password1);
            response.addCookie(role1);
        }
        return new R(true,login!=0?"登录成功(*^_^*)":"登录失败,账号或密码错误");
    }
}
